package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import com.auto.learning.R;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.WeChatData;
import com.auto.learning.event.Handle;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.sharesdk.tools.SnsLogin;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;

/**
 * 绑定账号
 */
public class BundingActivity extends BaseActivity implements OnClickListener,Callback {
	
	private final static int BIND_WEIXIN_SUCCESS = 1;
	private final static int USER_BIND_TEL_SUCCESS = 3;
	
	private RelativeLayout rel_bunding_mobile,rel_bunding_wechat,rel_bunding_qq,rel_bunding_company;
	private TextView tv_tel,tv_wechat,tv_qq,tv_company,tv_tel_num,tv_company_name;
	private boolean isNeedRefreshUi = false;
	private boolean bindCompanySuccess = false;
	
	
	private Handle handle = new Handle(this){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result = (ResponeResult) msg.obj;
				if (result != null) {
					//{"result":{"code":0,"msg":"操作成功"},"data":{"needFresh":1,"userId":13780}}
					try {
						JSONObject json = new JSONObject(result.getData());
						int userId = json.getInt("userId");
						int needFresh = json.getInt("needFresh");
						SharedPreferencesUtils.setParam(BundingActivity.this, HttpRequestHelper.USERID, userId);
						isNeedRefreshUi = needFresh == 2;
						MyUserInfo.getInstance().getUserInfoBean().setIsBindQq(2);
						checkBindStatus();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				CommonMethod.makeNotice(BundingActivity.this, msg.obj+"");
				break;
			case BIND_WEIXIN_SUCCESS:
				ResponeResult mResult = (ResponeResult) msg.obj;
				if (mResult != null) {
					try {
						JSONObject json = new JSONObject(mResult.getData());
						int userId = json.getInt("userId");
						int needFresh = json.getInt("needFresh");
						SharedPreferencesUtils.setParam(BundingActivity.this, HttpRequestHelper.USERID, userId);
						isNeedRefreshUi = needFresh == 2;
						MyUserInfo.getInstance().getUserInfoBean().setIsBindWeixin(2);
						checkBindStatus();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				break;
			case USER_BIND_TEL_SUCCESS:
				ResponeResult telResult = (ResponeResult) msg.obj;
				if (telResult != null) {
					try {
						JSONObject json = new JSONObject(telResult.getData());
						int userId = json.getInt("userId");
						int needFresh = json.getInt("needFresh");
						SharedPreferencesUtils.setParam(BundingActivity.this, HttpRequestHelper.USERID, userId);
						isNeedRefreshUi = needFresh == 2;
						if (!TextUtils.isEmpty(tel)) {
							MyUserInfo.getInstance().getUserInfoBean().setTel(tel);
							tel = "";
						}
						MyUserInfo.getInstance().getUserInfoBean().setIsBindTel(2);
						checkBindStatus();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				break;
			}
		};
	};
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setViewInLine(R.layout.bunding_activity);
		initView();
		TemporaryVariable.activities.push(this);
	}
	
	private void initView(){
		setTitle(R.string.favor_08);
		hideRight();
		tv_company_name = (TextView) findViewById(R.id.tv_company_name);
		tv_tel_num = (TextView) findViewById(R.id.tv_tel_num);
		tv_tel = (TextView) findViewById(R.id.tv_tel);
		tv_wechat = (TextView) findViewById(R.id.tv_wechat);
		tv_qq = (TextView) findViewById(R.id.tv_qq);
		tv_company = (TextView) findViewById(R.id.tv_company);
		rel_bunding_mobile = (RelativeLayout) findViewById(R.id.rel_bunding_mobile);
		rel_bunding_wechat = (RelativeLayout) findViewById(R.id.rel_bunding_wechat);
		rel_bunding_qq = (RelativeLayout) findViewById(R.id.rel_bunding_qq);
		rel_bunding_company = (RelativeLayout) findViewById(R.id.rel_bunding_company);
		rel_bunding_mobile.setOnClickListener(this);
		rel_bunding_wechat.setOnClickListener(this);
		rel_bunding_qq.setOnClickListener(this);
		rel_bunding_company.setOnClickListener(this);
		checkBindStatus();
		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (isNeedRefreshUi) {
					setResult(206);
				}else if (bindCompanySuccess) {
					setResult(207);
				}
				finish();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rel_bunding_mobile:
			Intent intent = new Intent(this, RegeditActivity.class);
			intent.putExtra("type", 3);
			startActivityForResult(intent,100);
			break;
		case R.id.rel_bunding_wechat:
			new SnsLogin(this,this).authorize(ShareSDK.getPlatform(Wechat.NAME));
			break;
		case R.id.rel_bunding_qq:
			new SnsLogin(this,this).authorize(ShareSDK.getPlatform(QQ.NAME));
			break;
		case R.id.rel_bunding_company:
			Intent mIntent = new Intent(this, CompanyRecommendActivity.class);
			startActivityForResult(mIntent,100);
			break;
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		  case SnsLogin.MSG_AUTH_COMPLETE: 
			CommonMethod.makeNotice(this,getString(R.string.auth_complete));
			WeChatData weChatData = (WeChatData) msg.obj;
			BindSns(weChatData);
			break;
		}
		return false;
	}
	String tel;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100) {
			if (resultCode == 210) {
				tel = data.getStringExtra("user_tel");
				HttpRequestHelper.BindTel(BundingActivity.this, tel, "", handle,USER_BIND_TEL_SUCCESS);
			}else if (resultCode == 211){
				checkBindStatus();
			}else if (resultCode == 212) {
				bindCompanySuccess = true;
				checkBindStatus();
			}
		}
	}
	
	/**
	 * 用户绑定微信、QQ
	 */
	private void BindSns(WeChatData weChatData){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(BundingActivity.this, HttpRequestHelper.USERID, 0))));
		String url = "";
		if (weChatData.getPlat() == 0) {
			url = HttpRequestHelper.USER_BIND_WEIXIN;
			params.add(new BasicNameValuePair("weixinId", weChatData.getUserId()));
		}else {
			url = HttpRequestHelper.USER_BIND_QQ;
			params.add(new BasicNameValuePair("qqId", weChatData.getUserId()));
		}
		params.add(new BasicNameValuePair("nickName", weChatData.getNickname()));
		params.add(new BasicNameValuePair("faceUrl", weChatData.getHeadimgurl()));
		HttpRequestHelper.executeHttpData(BundingActivity.this, url, params, handle, weChatData.getPlat() == 0 ? BIND_WEIXIN_SUCCESS : HttpRequestHelper.GETDATA_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}
	
	
	/**
	 * 检查绑定状态
	 */
	private void checkBindStatus(){
		if (TextUtils.isEmpty(MyUserInfo.getInstance().getUserInfoBean().getCompanyName())) {
			tv_company_name.setText("");
			tv_company_name.setVisibility(View.GONE);
		}else {
			tv_company_name.setText(MyUserInfo.getInstance().getUserInfoBean().getCompanyName());
			tv_company_name.setVisibility(View.VISIBLE);
		}
		if (TextUtils.isEmpty(MyUserInfo.getInstance().getUserInfoBean().getTel())) {
			tv_tel_num.setText("");
			tv_tel_num.setVisibility(View.GONE);
		}else {
			tv_tel_num.setText(MyUserInfo.getInstance().getUserInfoBean().getTel());
			tv_tel_num.setVisibility(View.VISIBLE);
		}
		
		if (MyUserInfo.getInstance().getUserInfoBean().getIsBindTel() == 1) {
			tv_tel.setText(getString(R.string.goto_bunding));
		}else {
			tv_tel.setText(getString(R.string.has_bunding));
		}
		
		if (MyUserInfo.getInstance().getUserInfoBean().getIsBindWeixin() == 1) {
			tv_wechat.setText(getString(R.string.goto_bunding));
		}else {
			tv_wechat.setText(getString(R.string.has_bunding));
		}
		
		if (MyUserInfo.getInstance().getUserInfoBean().getIsBindQq() == 1) {
			tv_qq.setText(getString(R.string.goto_bunding));
		}else {
			tv_qq.setText(getString(R.string.has_bunding));
		}
		
		if (TextUtils.isEmpty(MyUserInfo.getInstance().getUserInfoBean().getCompanyName())) {
			tv_company.setText(getString(R.string.goto_bunding));
		}else {
			tv_company.setText(getString(R.string.has_bunding));
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		TemporaryVariable.activities.removeElement(this);
		super.onDestroy();
	}
}
